package org.sauceggplant.item.man.ui.panel;

import com.alibaba.fastjson2.JSON;
import org.apache.commons.lang3.StringUtils;
import org.sauceggplant.item.man.dto.TypeDto;
import org.sauceggplant.item.man.po.Type;
import org.sauceggplant.item.man.service.TypeService;
import org.sauceggplant.item.man.service.impl.TypeServiceImpl;
import org.sauceggplant.item.man.ui.frame.MainFrame;
import org.sauceggplant.item.man.ui.table.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.List;

public class TypePanel extends JPanel {

    private static final Logger logger = LoggerFactory.getLogger(TypePanel.class);

    private MainFrame frame;

    private DataTable dataTable;

    private CardPanel cardPanel;

    private TypeService typeService = new TypeServiceImpl();

    private JTextField nameField = new JTextField(15);

    private JTextField queryParamValue;

    //卡片数据
    private Type type;

    //列表数据
    private List<Type> typeList;

    private String[] columnNames = new String[]{"序号", "名称"};

    private ItemPanel itemPanel;

    public TypePanel(ItemPanel itemPanel, MainFrame frame) {
        this.itemPanel = itemPanel;
        this.frame = frame;
        init();
    }

    private void init() {
        this.setLayout(new BorderLayout());
        initData();
        JScrollPane pane = new JScrollPane(dataTable);
        pane.setBorder(new TitledBorder(new EmptyBorder(5, 5, 5, 5), ""));
        this.add(pane, BorderLayout.CENTER);
        //initToolBar();
        JLabel nameLabel = new JLabel("名称", SwingConstants.RIGHT);

        JLabel nullLabel = new JLabel("");
        nullLabel.setEnabled(false);
        Component[][] rowData = new Component[][]{
                {
                        nameLabel,
                        nameField
                }
        };
        cardPanel = new CardPanel(rowData, new JLabel("类别名称"));
        queryParamValue = cardPanel.getQueryParamValue();
        cardPanel.getQuery().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshTable(loadData(queryParamValue.getText()));
            }
        });
        cardPanel.getAdd().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                type = new Type();
                type.setName(nameField.getText());
                typeService.insert(type);
                refreshTable(loadData(queryParamValue.getText()));
            }
        });
        cardPanel.getSave().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (null == type || null == type.getId()) {
                    JOptionPane.showMessageDialog(cardPanel, "请选择一行数据进行更改", "温馨提示", JOptionPane.WARNING_MESSAGE);
                } else {
                    type.setName(nameField.getText());
                    typeService.update(type);
                    refreshTable(loadData(queryParamValue.getText()));
                }
            }
        });
        cardPanel.getDelete().addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (null == type || null == type.getId()) {
                    JOptionPane.showMessageDialog(cardPanel, "请选择一行数据进行删除", "温馨提示", JOptionPane.WARNING_MESSAGE);
                } else {
                    typeService.delete(type.getId());
                    refreshTable(loadData(queryParamValue.getText()));
                }
            }
        });
        this.add(cardPanel, BorderLayout.NORTH);
    }

    private void initData() {
        String queryParam;
        if (null == queryParamValue) {
            queryParam = "";
        } else {
            queryParam = queryParamValue.getText();
        }
        Object[][] rowData = loadData(queryParam);
        dataTable = new DataTable(rowData, columnNames, frame);
        dataTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int selectedRow = dataTable.getSelectedRow();
                if (selectedRow > -1 && selectedRow < typeList.size()) {
                    type = typeList.get(selectedRow);
                    nameField.setText(typeList.get(selectedRow).getName());
                }
            }
        });
    }

    private void refreshTable(Object[][] rowData) {
        int columnLength = 2;
        DefaultTableModel tableModel = new DefaultTableModel(rowData.length, columnLength);
        for (int i = 0; i < rowData.length; i++) {
            for (int j = 0; j < columnLength; j++) {
                tableModel.setValueAt(rowData[i][j], i, j);
            }
        }
        tableModel.setColumnIdentifiers(columnNames);
        dataTable.setModel(tableModel);
        dataTable.updateUI();
    }

    private Object[][] loadData(String queryParamValue) {
        TypeDto typeDto = new TypeDto();
        typeDto.setOffset(0L);
        typeDto.setSize(100000L);
        if (StringUtils.isNoneBlank(queryParamValue)) {
            typeDto.setNameIsLike(queryParamValue);
        }
        typeDto.setOrder("`name asc`");
        typeList = typeService.findAll(typeDto);
        logger.info(JSON.toJSONString(typeList));
        Object[][] rowData = new Object[typeList.size()][2];
        for (int index = 0; index < typeList.size(); index++) {
            Type type = typeList.get(index);
            rowData[index][0] = CardPanel.getIndex(index + 1);
            rowData[index][1] = type.getName();
        }
        itemPanel.getQueryParamValue().setText("");
        itemPanel.refreshTable(itemPanel.loadData(""));
        return rowData;
    }
}
